#include "core/enhanced_chat_system.h"
#include <iostream>
#include <string>
#include <sstream>
#include <vector>

class SimpleChatClient {
private:
    EnhancedChatSystem& chatSystem;
    std::string currentUser;
    bool isLoggedIn;
    
public:
    SimpleChatClient(EnhancedChatSystem& system) : chatSystem(system), isLoggedIn(false) {}
    
    void showWelcome() {
        std::cout << "\n" << std::string(50, '=') << std::endl;
        std::cout << "    🚀 简单聊天客户端 - 单聊演示" << std::endl;
        std::cout << std::string(50, '=') << std::endl;
    }
    
    void showHelp() {
        std::cout << "\n📋 可用命令:" << std::endl;
        std::cout << "  login <username>        - 登录系统" << std::endl;
        std::cout << "  chat <username>         - 开始与用户聊天" << std::endl;
        std::cout << "  send <username> <msg>   - 发送消息给用户" << std::endl;
        std::cout << "  history <username>      - 查看与用户的聊天记录" << std::endl;
        std::cout << "  list                    - 查看我的私聊列表" << std::endl;
        std::cout << "  users                   - 查看在线用户" << std::endl;
        std::cout << "  help                    - 显示帮助" << std::endl;
        std::cout << "  quit                    - 退出程序" << std::endl;
    }
    
    bool login(const std::string& username) {
        if (isLoggedIn) {
            std::cout << "❌ 已经登录为: " << currentUser << std::endl;
            return false;
        }
        
        // 模拟socket连接，这里使用假的socket ID
        int fakeSocketId = 1000 + rand() % 1000;
        
        if (chatSystem.addUser(username, fakeSocketId, "127.0.0.1")) {
            currentUser = username;
            isLoggedIn = true;
            std::cout << "✅ 登录成功! 欢迎 " << username << std::endl;
            return true;
        } else {
            std::cout << "❌ 登录失败! 用户名可能已被使用" << std::endl;
            return false;
        }
    }
    
    void startChat(const std::string& targetUser) {
        if (!isLoggedIn) {
            std::cout << "❌ 请先登录!" << std::endl;
            return;
        }
        
        if (targetUser == currentUser) {
            std::cout << "❌ 不能和自己聊天!" << std::endl;
            return;
        }
        
        // 检查目标用户是否存在
        if (!chatSystem.isUserOnline(targetUser)) {
            std::cout << "⚠️  用户 " << targetUser << " 不在线，但仍可发送消息" << std::endl;
        }
        
        // 创建或获取私聊会话
        std::string chatId = chatSystem.startPrivateChat(currentUser, targetUser);
        std::cout << "💬 开始与 " << targetUser << " 的私聊 (会话ID: " << chatId << ")" << std::endl;
        
        // 显示历史消息
        auto chat = chatSystem.getPrivateChat(currentUser, targetUser);
        if (chat && !chat->messages.empty()) {
            std::cout << "\n📋 历史消息:" << std::endl;
            for (const auto& msg : chat->messages) {
                std::cout << "  [" << msg.fromUser << "] " << msg.content << std::endl;
            }
        }
        
        std::cout << "\n💡 现在可以使用 'send " << targetUser << " <消息>' 发送消息" << std::endl;
    }
    
    void sendMessage(const std::string& targetUser, const std::string& message) {
        if (!isLoggedIn) {
            std::cout << "❌ 请先登录!" << std::endl;
            return;
        }
        
        if (targetUser == currentUser) {
            std::cout << "❌ 不能给自己发消息!" << std::endl;
            return;
        }
        
        if (message.empty()) {
            std::cout << "❌ 消息不能为空!" << std::endl;
            return;
        }
        
        bool success = chatSystem.sendPrivateMessage(currentUser, targetUser, message);
        if (success) {
            std::cout << "✅ 消息已发送给 " << targetUser << ": " << message << std::endl;
            
            // 模拟对方在线并回复 (仅演示用)
            if (chatSystem.isUserOnline(targetUser)) {
                std::cout << "📱 " << targetUser << " 已收到消息" << std::endl;
            } else {
                std::cout << "📤 " << targetUser << " 离线，消息已保存" << std::endl;
            }
        } else {
            std::cout << "❌ 消息发送失败!" << std::endl;
        }
    }
    
    void showChatHistory(const std::string& targetUser) {
        if (!isLoggedIn) {
            std::cout << "❌ 请先登录!" << std::endl;
            return;
        }
        
        auto chat = chatSystem.getPrivateChat(currentUser, targetUser);
        if (!chat) {
            std::cout << "📭 与 " << targetUser << " 没有聊天记录" << std::endl;
            return;
        }
        
        std::cout << "\n💬 与 " << targetUser << " 的聊天记录:" << std::endl;
        std::cout << "会话ID: " << chat->chatId << std::endl;
        std::cout << "创建时间: " << chat->createTime << std::endl;
        std::cout << "最后活跃: " << chat->lastActiveTime << std::endl;
        std::cout << "消息数量: " << chat->messages.size() << " 条" << std::endl;
        
        if (!chat->messages.empty()) {
            std::cout << "\n消息历史:" << std::endl;
            for (size_t i = 0; i < chat->messages.size(); ++i) {
                const auto& msg = chat->messages[i];
                std::cout << "  " << (i + 1) << ". [" << msg.fromUser << "] " 
                          << msg.content << " (" << msg.timestamp << ")" << std::endl;
            }
        }
    }
    
    void showPrivateChats() {
        if (!isLoggedIn) {
            std::cout << "❌ 请先登录!" << std::endl;
            return;
        }
        
        auto user = chatSystem.getUser(currentUser);
        if (!user || user->privateChats.empty()) {
            std::cout << "📭 没有私聊记录" << std::endl;
            return;
        }
        
        std::cout << "\n👤 " << currentUser << " 的私聊列表:" << std::endl;
        int index = 1;
        for (const std::string& chatId : user->privateChats) {
            std::cout << "  " << index++ << ". " << chatId;
            
            // 获取聊天详情
            std::string user1, user2;
            size_t pos = chatId.find('_');
            if (pos != std::string::npos) {
                user1 = chatId.substr(0, pos);
                user2 = chatId.substr(pos + 1);
                std::string otherUser = (user1 == currentUser) ? user2 : user1;
                
                auto chat = chatSystem.getPrivateChat(currentUser, otherUser);
                if (chat) {
                    std::cout << " (与 " << otherUser << ", " 
                              << chat->messages.size() << " 条消息)";
                }
            }
            std::cout << std::endl;
        }
    }
    
    void showOnlineUsers() {
        auto users = chatSystem.getOnlineUsers();
        std::cout << "\n👥 在线用户 (" << users.size() << " 人):" << std::endl;
        
        for (size_t i = 0; i < users.size(); ++i) {
            std::cout << "  " << (i + 1) << ". " << users[i]->userId;
            if (users[i]->userId == currentUser) {
                std::cout << " (我)";
            }
            std::cout << " - " << users[i]->ip << std::endl;
        }
    }
    
    std::vector<std::string> parseCommand(const std::string& input) {
        std::vector<std::string> tokens;
        std::istringstream iss(input);
        std::string token;
        
        while (iss >> token) {
            tokens.push_back(token);
        }
        
        return tokens;
    }
    
    void processCommand(const std::string& input) {
        auto tokens = parseCommand(input);
        if (tokens.empty()) return;
        
        std::string command = tokens[0];
        
        if (command == "help") {
            showHelp();
        }
        else if (command == "login") {
            if (tokens.size() < 2) {
                std::cout << "❌ 用法: login <username>" << std::endl;
            } else {
                login(tokens[1]);
            }
        }
        else if (command == "chat") {
            if (tokens.size() < 2) {
                std::cout << "❌ 用法: chat <username>" << std::endl;
            } else {
                startChat(tokens[1]);
            }
        }
        else if (command == "send") {
            if (tokens.size() < 3) {
                std::cout << "❌ 用法: send <username> <message>" << std::endl;
            } else {
                std::string message;
                for (size_t i = 2; i < tokens.size(); ++i) {
                    if (i > 2) message += " ";
                    message += tokens[i];
                }
                sendMessage(tokens[1], message);
            }
        }
        else if (command == "history") {
            if (tokens.size() < 2) {
                std::cout << "❌ 用法: history <username>" << std::endl;
            } else {
                showChatHistory(tokens[1]);
            }
        }
        else if (command == "list") {
            showPrivateChats();
        }
        else if (command == "users") {
            showOnlineUsers();
        }
        else if (command == "quit") {
            std::cout << "👋 再见!" << std::endl;
            exit(0);
        }
        else {
            std::cout << "❌ 未知命令: " << command << std::endl;
            std::cout << "💡 输入 'help' 查看可用命令" << std::endl;
        }
    }
    
    void run() {
        showWelcome();
        showHelp();
        
        std::string input;
        while (true) {
            std::cout << "\n> ";
            std::getline(std::cin, input);
            
            if (!input.empty()) {
                processCommand(input);
            }
        }
    }
};

// 模拟多用户环境
void setupDemoUsers(EnhancedChatSystem& chatSystem) {
    // 预先创建一些演示用户
    chatSystem.addUser("Bob", 2001, "192.168.1.101");
    chatSystem.addUser("Charlie", 2002, "192.168.1.102");
    chatSystem.addUser("David", 2003, "192.168.1.103");
    
    // 创建一些演示对话
    chatSystem.sendPrivateMessage("Bob", "Charlie", "Hi Charlie, how are you?");
    chatSystem.sendPrivateMessage("Charlie", "Bob", "I'm fine, thanks!");
    chatSystem.sendPrivateMessage("Bob", "David", "Hey David!");
}

int main() {
    // 创建聊天系统
    EnhancedChatSystem chatSystem;
    
    // 设置演示环境
    setupDemoUsers(chatSystem);
    
    // 创建并运行客户端
    SimpleChatClient client(chatSystem);
    
    std::cout << "💡 演示提示:" << std::endl;
    std::cout << "  - 已有用户: Bob, Charlie, David" << std::endl;
    std::cout << "  - 可以登录为 Alice 并与他们聊天" << std::endl;
    std::cout << "  - 或者创建新用户名登录" << std::endl;
    
    client.run();
    
    return 0;
} 